package sdkshell.kuaiyan.com.kuaiyansdk.util;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
*   Created by admin on 2016/8/29.
*/
public class StringUtils {
    public static StringBuilder getUrlFromUrlAndParams(String url, Map<String, String> params) {
        if(url == null){
            url = "url = null,未调用net.setUlr方法";
        }
        StringBuilder stringBuilder = new StringBuilder(url);
        if (params != null || params.size() != 0) {
            if(url.contains("?")) {
                stringBuilder.append("&");
            }else{
                stringBuilder.append("?");
            }
            boolean first = true;
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (!first) {
                    stringBuilder.append("&");
                }
                stringBuilder.append(entry.getKey() + "=" + entry.getValue());
                first = false;
            }
        }
        return stringBuilder;
    }

    public static StringBuilder MapToString(Map<String, String> params) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (params != null || params.size() != 0) {
            boolean first = true;
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (!first) {
                    stringBuilder.append("&");
                }
                stringBuilder.append(entry.getKey() + "=" + entry.getValue());
                first = false;
            }
        }
        return stringBuilder;
    }

    /**
     * 获取所有的参数
     * @param args
     * @return
     */
    public static String getArgs(Object[] args){
        StringBuilder stringBuilder = new StringBuilder();
        if(args == null||args.length == 0){
            stringBuilder.append("args = null");
        }else {
            for (int i = 0; i < args.length; i++) {
                Object o = args[i];
                String ar = o == null ? "null" : o.toString();
                stringBuilder.append("参数" + i + "=" + ar);
            }
        }
        return stringBuilder.toString();
    }

    /**
     * 获取url参数
     * @param url
     * @return
     */
    public static Map<String,String> getArgs(String url){
        Map<String,String> map = new HashMap<>();
        Pattern pattern = Pattern.compile("[\\?&]\\s*([^=]+)=\\s*([^(\\?)^&]+)");
        Matcher matcher = pattern.matcher(url);
        while(matcher.find()){
            map.put(matcher.group(1),matcher.group(2));
        }
        return map;
    }

}
